﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection.Emit;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace net.notdot.XmlOd {
    class Program {
        static void Main(string[] args) {
            AssemblyName name = new AssemblyName(args[args.Length - 1]);
            AssemblyBuilder prog = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);
            
            ConstructorInfo daCtor = typeof(DebuggableAttribute).GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
            CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] { DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations });
            prog.SetCustomAttribute(daBuilder);

            ModuleBuilder module = prog.DefineDynamicModule(args[args.Length - 1], args[args.Length - 1], true);
            XmlSerializer serializer = new XmlSerializer(typeof(ODCode));
            for (int i = 0; i < args.Length - 1; i++) {
                Stream instream = new FileStream(args[i], FileMode.Open, FileAccess.Read, FileShare.Read);
                ODCode code = serializer.Deserialize(instream) as ODCode;
                code.Compile(prog, module);
            }
            prog.Save(args[args.Length - 1]);
        }
    }
}
